/*
 *******************************************************************************
 *
 * Copyright (C) 2019-2020 Dialog Semiconductor.
 * This computer program includes Confidential, Proprietary Information
 * of Dialog Semiconductor. All Rights Reserved.
 *
 *******************************************************************************
 */

package com.example.suota.suota.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

/**
 * Custom Dialog Fragment
 */
public class SupportCustomDialogFragment extends DialogFragment {
    private static final String TAG = "SupportDialogFragment";

    private DialogFragmentManager dialogFragmentManager;

    public int getType() {
        return dialogFragmentManager.getDialogType();
    }

    // for progress dialog
    static SupportCustomDialogFragment newInstance(int type, int layoutResourceId, boolean cancelable, boolean cancelableOnOutside, DialogFragmentManager dialogFragmentManager) {
        SupportCustomDialogFragment fragment = new SupportCustomDialogFragment();
        fragment.setArguments(DialogFragmentManager.createArgumentsBundle(type, cancelableOnOutside, layoutResourceId, cancelable, dialogFragmentManager));
        return fragment;
    }

    // for alert dialog
    static SupportCustomDialogFragment newInstance(int type, @NonNull String title, @NonNull String message, String positive, String negative, int iconResourceId, boolean cancelable, boolean cancelableOnOutside, DialogFragmentManager dialogFragmentManager) {
        SupportCustomDialogFragment fragment = new SupportCustomDialogFragment();
        fragment.setArguments(DialogFragmentManager.createArgumentsBundle(type, cancelableOnOutside, title, message, positive, negative, iconResourceId, cancelable, dialogFragmentManager));
        return fragment;
    }

    /**
     * Shows dialog removing the previous displayed SupportCustomDialogFragment if still visible.
     *
     * @param fragmentManager the fragment manager used to make the appropriate transaction
     */
    public void showDialog(FragmentManager fragmentManager) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment previousShown = fragmentManager.findFragmentByTag(SupportCustomDialogFragment.class.getSimpleName());
        if (previousShown != null)
            transaction.remove(previousShown);
        show(transaction, SupportCustomDialogFragment.class.getSimpleName());
    }

    public void setOnPositiveClickListener(DialogFragmentManager.OnResponseListener onPositiveClickListener) {
        if (dialogFragmentManager == null) {
            dialogFragmentManager = getArguments().getParcelable(DialogFragmentManager.DIALOG_MANAGER);
            if (dialogFragmentManager == null)
                return;
        }

        dialogFragmentManager.setOnPositiveClickListener(onPositiveClickListener);
    }

    public void setOnNegativeClickListener(DialogFragmentManager.OnResponseListener onNegativeClickListener) {
        if (dialogFragmentManager == null) {
            dialogFragmentManager = getArguments().getParcelable(DialogFragmentManager.DIALOG_MANAGER);
            if (dialogFragmentManager == null)
                return;
        }

        dialogFragmentManager.setOnNegativeClickListener(onNegativeClickListener);
    }

    public void setOnDismissListener(DialogFragmentManager.OnResponseListener onDismissListener) {
        if (dialogFragmentManager == null) {
            dialogFragmentManager = getArguments().getParcelable(DialogFragmentManager.DIALOG_MANAGER);
            if (dialogFragmentManager == null)
                return;
        }

        dialogFragmentManager.setOnDismissListener(onDismissListener);
    }

    public void setOnDialogBackPressedListener(DialogFragmentManager.OnResponseListener onDialogBackPressedListener) {
        if (dialogFragmentManager == null) {
            dialogFragmentManager = getArguments().getParcelable(DialogFragmentManager.DIALOG_MANAGER);
            if (dialogFragmentManager == null)
                return;
        }

        dialogFragmentManager.setOnDialogBackPressedListener(onDialogBackPressedListener);
    }

    public void setOnViewCreatedListener(DialogFragmentManager.OnViewCreatedListener onViewCreatedListener) {
        if (dialogFragmentManager == null) {
            dialogFragmentManager = getArguments().getParcelable(DialogFragmentManager.DIALOG_MANAGER);
            if (dialogFragmentManager == null)
                return;
        }

        dialogFragmentManager.setOnViewCreatedListener(onViewCreatedListener);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getArguments().containsKey(DialogFragmentManager.LAYOUT_KEY))
            return dialogFragmentManager.onCreateView(inflater, container, getArguments().getInt(DialogFragmentManager.LAYOUT_KEY));

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if (getArguments().containsKey(DialogFragmentManager.LAYOUT_KEY)) {
            Dialog dialog = super.onCreateDialog(savedInstanceState);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialogFragmentManager.setCancellation(dialog, getArguments());
            return dialog;
        }
        return dialogFragmentManager.onCreateDialog(getArguments(), getActivity());
    }


    @Override
    public void onResume() {
        super.onResume();
        if (dialogFragmentManager.onBackPressesListenerHasBeenSet() && isCancelable()) {
            // if the DialogFragment is cancelable we trigger the appropriate callback
            dialogFragmentManager.handleBackPressed(getDialog());
        }
    }

    /**
     * Safely dismiss the dialog if possible.
     */
    @Override
    public void dismiss() {
        if (getDialog() == null || !getDialog().isShowing() || isRemoving())
            return;

        try {
            super.dismiss();
        } catch (IllegalStateException e) {
            // gets triggered if user leaves the app, while connecting to device
            // if he doesn't return to app before the dialog gets to onDismiss then this exception gets triggered
            Log.i(TAG, e.getMessage());
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        dialogFragmentManager.onDismiss();
    }

    public DialogFragmentManager getDialogFragmentManager() {
        return dialogFragmentManager;
    }

    public void setDialogFragmentManager(DialogFragmentManager dialogFragmentManager) {
        this.dialogFragmentManager = dialogFragmentManager;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (dialogFragmentManager == null)
            dialogFragmentManager = getArguments().getParcelable(DialogFragmentManager.DIALOG_MANAGER);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        dialogFragmentManager.removeAllListeners();
    }
}
